package com.agrimall.servlet.client;

import com.agrimall.entity.Cart;
import com.agrimall.entity.User;
import com.agrimall.service.CartService;
import com.agrimall.service.ProductService;
import com.agrimall.service.UserService;
import com.agrimall.service.impl.CartServiceImpl;
import com.agrimall.service.impl.ProductServiceImpl;
import com.agrimall.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * 客户端购物车管理Servlet
 */
@WebServlet("/client/cart")
public class CartServlet extends HttpServlet {
    private CartService cartService = new CartServiceImpl();
    private UserService userService = new UserServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        String action = request.getParameter("action");
        
        if (action == null || action.equals("") || action.equals("list")) {
            // 购物车列表
            listCart(request, response, user);
        } else if (action.equals("count")) {
            // 获取购物车数量
            getCartCount(request, response, user);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print("{\"success\":false,\"message\":\"请先登录\"}");
            out.flush();
            return;
        }
        
        String action = request.getParameter("action");
        
        if (action != null && action.equals("add")) {
            // 添加购物车
            addToCart(request, response, user);
        } else if (action != null && action.equals("update")) {
            // 更新购物车数量
            updateCart(request, response, user);
        } else if (action != null && action.equals("delete")) {
            // 删除购物车项
            deleteCart(request, response, user);
        } else if (action != null && action.equals("checkout")) {
            // 批量结算
            checkoutCart(request, response, user);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    /**
     * 购物车列表
     */
    private void listCart(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        try {
            List<Cart> cartList = cartService.getCartList(user.getUserId());
            request.setAttribute("cartList", cartList);
            request.getRequestDispatcher("/client/cart/list.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "加载购物车失败：" + e.getMessage());
            request.getRequestDispatcher("/client/cart/list.jsp").forward(request, response);
        }
    }
    
    /**
     * 获取购物车数量
     */
    private void getCartCount(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            int count = cartService.getCartCount(user.getUserId());
            out.print("{\"success\":true,\"count\":" + count + "}");
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"count\":0}");
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 添加购物车
     */
    private void addToCart(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String productIdStr = request.getParameter("productId");
            String quantityStr = request.getParameter("quantity");
            
            if (productIdStr == null || quantityStr == null) {
                out.print("{\"success\":false,\"message\":\"参数错误\"}");
                return;
            }
            
            Long productId = Long.parseLong(productIdStr);
            Integer quantity = Integer.parseInt(quantityStr);
            
            if (quantity <= 0) {
                out.print("{\"success\":false,\"message\":\"数量必须大于0\"}");
                return;
            }
            
            boolean success = cartService.addToCart(user.getUserId(), productId, quantity);
            if (success) {
                out.print("{\"success\":true,\"message\":\"已添加到购物车\"}");
            } else {
                try {
                    ProductService productService = new ProductServiceImpl();
                    com.agrimall.entity.Product product = productService.getProductById(productId);
                    if (product == null) {
                        out.print("{\"success\":false,\"message\":\"商品不存在\"}");
                    } else if (product.getStatus() == null || product.getStatus() == 0) {
                        out.print("{\"success\":false,\"message\":\"商品已下架\"}");
                    } else if (product.getStock() == null || product.getStock() < quantity) {
                        out.print("{\"success\":false,\"message\":\"库存不足，当前库存：" + (product.getStock() != null ? product.getStock() : 0) + "\"}");
                    } else {
                        out.print("{\"success\":false,\"message\":\"添加失败，请重试\"}");
                    }
                } catch (Exception e) {
                    out.print("{\"success\":false,\"message\":\"添加失败，商品可能已下架或库存不足\"}");
                }
            }
        } catch (NumberFormatException e) {
            out.print("{\"success\":false,\"message\":\"参数格式错误\"}");
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"服务器错误：" + e.getMessage() + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 更新购物车数量
     */
    private void updateCart(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String cartIdStr = request.getParameter("cartId");
            String quantityStr = request.getParameter("quantity");
            
            if (cartIdStr == null || quantityStr == null) {
                out.print("{\"success\":false,\"message\":\"参数错误\"}");
                return;
            }
            
            Long cartId = Long.parseLong(cartIdStr);
            Integer quantity = Integer.parseInt(quantityStr);
            
            if (quantity <= 0) {
                out.print("{\"success\":false,\"message\":\"数量必须大于0\"}");
                return;
            }
            
            boolean success = cartService.updateQuantity(cartId, quantity);
            if (success) {
                out.print("{\"success\":true,\"message\":\"更新成功\"}");
            } else {
                out.print("{\"success\":false,\"message\":\"更新失败，商品可能已下架或库存不足\"}");
            }
        } catch (NumberFormatException e) {
            out.print("{\"success\":false,\"message\":\"参数格式错误\"}");
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"服务器错误\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 删除购物车项
     */
    private void deleteCart(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String cartIdStr = request.getParameter("cartId");
            
            if (cartIdStr == null) {
                out.print("{\"success\":false,\"message\":\"参数错误\"}");
                return;
            }
            
            Long cartId = Long.parseLong(cartIdStr);
            boolean success = cartService.removeFromCart(cartId);
            
            if (success) {
                out.print("{\"success\":true,\"message\":\"删除成功\"}");
            } else {
                out.print("{\"success\":false,\"message\":\"删除失败\"}");
            }
        } catch (NumberFormatException e) {
            out.print("{\"success\":false,\"message\":\"参数格式错误\"}");
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"服务器错误\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 批量结算购物车
     */
    private void checkoutCart(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String[] cartIdsArray = request.getParameterValues("cartIds[]");
            String deliveryAddress = request.getParameter("deliveryAddress");
            String receiverName = request.getParameter("receiverName");
            String receiverPhone = request.getParameter("receiverPhone");
            String paymentMethod = request.getParameter("paymentMethod");
            
            if (cartIdsArray == null || cartIdsArray.length == 0) {
                out.print("{\"success\":false,\"message\":\"请选择要结算的商品\"}");
                return;
            }
            
            if (deliveryAddress == null || deliveryAddress.trim().isEmpty() ||
                receiverName == null || receiverName.trim().isEmpty() ||
                receiverPhone == null || receiverPhone.trim().isEmpty()) {
                out.print("{\"success\":false,\"message\":\"请填写完整的收货信息\"}");
                return;
            }
            
            if (paymentMethod == null || paymentMethod.trim().isEmpty()) {
                paymentMethod = "余额支付";
            }
            
            List<Long> cartIds = new ArrayList<>();
            for (String cartIdStr : cartIdsArray) {
                try {
                    cartIds.add(Long.parseLong(cartIdStr));
                } catch (NumberFormatException e) {
                    // 忽略无效的ID
                }
            }
            
            if (cartIds.isEmpty()) {
                out.print("{\"success\":false,\"message\":\"请选择要结算的商品\"}");
                return;
            }
            
            // 更新用户地址
            user.setAddress(deliveryAddress.trim());
            userService.updateUser(user);
            
            boolean success = cartService.batchCreateOrders(user.getUserId(), cartIds, 
                    deliveryAddress.trim(), receiverName.trim(), receiverPhone.trim(), paymentMethod.trim());
            
            if (success) {
                User updatedUser = userService.getUserById(user.getUserId());
                if (updatedUser != null) {
                    request.getSession().setAttribute("user", updatedUser);
                }
                out.print("{\"success\":true,\"message\":\"结算成功\"}");
            } else {
                out.print("{\"success\":false,\"message\":\"结算失败，可能是余额不足、商品已下架或库存不足\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"服务器错误\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
}

